package encrypt

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"errors"
	"fmt"
	"io"
)

func Md5(stringIn string) (string, error) {
	if len(stringIn) == 0 {
		return stringIn, errors.New("输入字符串长度不能为0")
	}
	result, err := Md5Byte([]byte(stringIn))
	if err != nil {
		return "", err
	}
	return result, nil
}

func Md5Byte(byteIn []byte) (string, error) {
	h := md5.New()
	h.Write(byteIn)
	result := h.Sum(nil)
	result2 := fmt.Sprintf("%x", result)
	return result2, nil
}

func Sha1(stringIn string) (string, error) {
	if len(stringIn) == 0 {
		return stringIn, errors.New("输入字符串长度不能为0")
	}
	h := sha1.New()
	if _, err := io.WriteString(h, stringIn); err != nil {
		return "", err
	}
	result := fmt.Sprintf("%x", h.Sum(nil))
	return result, nil
}

func Sha256(stringIn string) (string, error) {
	if len(stringIn) == 0 {
		return stringIn, errors.New("输入字符串长度不能为0")
	}
	h := sha256.New()
	if _, err := io.WriteString(h, stringIn); err != nil {
		return "", err
	}
	result := fmt.Sprintf("%x", h.Sum(nil))
	return result, nil
}
